package com.wbao.dianniu.ui;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.mobileim.fundamental.widget.refreshlist.PullToRefreshBase.Mode;
import com.alibaba.mobileim.fundamental.widget.refreshlist.PullToRefreshBase.OnRefreshListener;
import com.alibaba.mobileim.fundamental.widget.refreshlist.PullToRefreshListView;
import com.umeng.analytics.MobclickAgent;
import com.wbao.dianniu.R;
import com.wbao.dianniu.adapter.RecruitListAdapter;
import com.wbao.dianniu.data.RecruitListData;
import com.wbao.dianniu.expandtabview.ExpandTabView;
import com.wbao.dianniu.expandtabview.RecruitViewRight;
import com.wbao.dianniu.expandtabview.ViewLeft;
import com.wbao.dianniu.expandtabview.ViewMiddle;
import com.wbao.dianniu.listener.IRecruitListListener;
import com.wbao.dianniu.logical.Const;
import com.wbao.dianniu.logical.GlobalContext;
import com.wbao.dianniu.manager.RecruitListManager;
import com.wbao.dianniu.utils.Notification;
import com.wbao.dianniu.utils.Utils;

import java.util.ArrayList;
import java.util.List;

/**
 * 找工作
 *
 * @author yejianjun
 */
public class ComRecruitActivity extends BaseActivity implements IRecruitListListener {
    private ExpandTabView expandTabView;
    private ArrayList<View> mViewArray = new ArrayList<View>();
    /**
     * 地区搜索
     */
    private ViewLeft viewLeft;
    /**
     * 薪资搜索
     */
    private ViewMiddle viewMiddle;
    /**
     * 工作经验搜索
     */
    private RecruitViewRight viewRight;
    private RecruitListManager manager;
    private List<RecruitListData> mList = new ArrayList<RecruitListData>();
    private RecruitListAdapter adapter;
    private PullToRefreshListView pullListView;
    private ListView listView;
    private ImageView searchBtn;
    private EditText searchET;
    private TextView noDataTV;
    private String strPost = "";
    private String strAddress = "";
    private String strSalary = "";
    private String strExperience = "";
    private final int PAGE_COUNTS = 10;
    private int currentPage = 0;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentLayout(R.layout.activity_company_recruit, LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT);
        setTitleName(getResources().getString(R.string.cover_hall));
        initView();
        initVaule();
        initListener();
        initData();

    }

    private void initView() {
        expandTabView = (ExpandTabView) findViewById(R.id.expandtab_view);
        viewLeft = new ViewLeft(this);
        viewMiddle = new ViewMiddle(this);
        viewRight = new RecruitViewRight(this);

        searchET = (EditText) findViewById(R.id.search_input_edittext01);
        noDataTV = (TextView) findViewById(R.id.no_find_data);
        searchBtn = (ImageView) findViewById(R.id.search_imagebutton01);
        searchBtn.setOnClickListener(this);

        pullListView = (PullToRefreshListView) findViewById(R.id.recruit_listView);
        pullListView.setMode(Mode.PULL_UP_TO_REFRESH);
        pullListView.setOnRefreshListener(onRefreshListener);
        listView = pullListView.getRefreshableView();
        registerForContextMenu(listView);
        searchET.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    Utils.hideSoftInput(ComRecruitActivity.this, searchET);
                    strPost = searchET.getText().toString().trim();
                    adapter.clear();
                    currentPage = 0;
                    requestData(currentPage * PAGE_COUNTS, PAGE_COUNTS, strPost, strAddress, strSalary, strExperience);
                    return true;
                }
                return false;
            }
        });
        searchET.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // TODO Auto-generated method stub

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
                // TODO Auto-generated method stub

            }

            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub
                strPost = searchET.getText().toString().trim();
            }
        });
    }

    private void initVaule() {
        mViewArray.add(viewLeft);
        mViewArray.add(viewMiddle);
        mViewArray.add(viewRight);
        ArrayList<String> mTextArray = new ArrayList<String>();
        mTextArray.add("地区");
        mTextArray.add("薪资");
        mTextArray.add("工作经验");
        expandTabView.setValue(mTextArray, mViewArray);
        expandTabView.setTitle(viewLeft.getShowText(), 0);
        expandTabView.setTitle(viewMiddle.getShowText(), 1);
        expandTabView.setTitle(viewRight.getShowText(), 2);
    }

    private void initListener() {
        viewLeft.setOnSelectListener(new ViewLeft.OnSelectListener() {

            @Override
            public void getValue(String showText) {
                onRefresh(viewLeft, showText);
                strAddress = showText;
                if (strAddress.contains("全部")) {
                    strAddress = "";
                }
                currentPage = 0;
                requestData(currentPage * PAGE_COUNTS, PAGE_COUNTS, strPost, strAddress, strSalary, strExperience);
            }
        });

        viewMiddle.setOnSelectListener(new ViewMiddle.OnSelectListener() {

            public void getValue(String distance, String showText) {
                onRefresh(viewMiddle, showText);
                strSalary = showText;
                if (strSalary.contains("不限")) {
                    strSalary = "";
                }
                currentPage = 0;
                requestData(currentPage * PAGE_COUNTS, PAGE_COUNTS, strPost, strAddress, strSalary, strExperience);
            }
        });

        viewRight.setOnSelectListener(new RecruitViewRight.OnSelectListener() {

            @Override
            public void getValue(String distance, String showText) {
                onRefresh(viewRight, showText);
                strExperience = showText;
                if (strExperience.contains("不限")) {
                    strExperience = "";
                }
                currentPage = 0;
                requestData(currentPage * PAGE_COUNTS, PAGE_COUNTS, strPost, strAddress, strSalary, strExperience);
            }
        });

    }

    private void onRefresh(View view, String showText) {

        expandTabView.onPressBack();
        int position = getPositon(view);
        if (position >= 0 && !expandTabView.getTitle(position).equals(showText)) {
            expandTabView.setTitle(showText, position);
        }
    }

    private void initData() {
        manager = new RecruitListManager(this);
        manager.addRecruitListener(this);
        adapter = new RecruitListAdapter(this);
        adapter.addData(mList);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(itemClickListener);
        requestData(currentPage, PAGE_COUNTS, null, null, null, null);
    }

    /**
     * @param page       页码
     * @param rows       每页多少条
     * @param post       搜索的职务名称
     * @param address    搜索的地址
     * @param salary     搜索的薪资
     * @param experience 搜索的工作经验
     */
    private void requestData(int page, int rows, String post, String address, String salary, String experience) {
        manager.recruitList(GlobalContext.getAccountId(), 1, page, rows, post, address, salary, experience);
    }

    private int getPositon(View tView) {
        for (int i = 0; i < mViewArray.size(); i++) {
            if (mViewArray.get(i) == tView) {
                return i;
            }
        }
        return -1;
    }

    @Override
    public void onBackPressed() {
        if (!expandTabView.onPressBack()) {
            finish();
        }
    }

    @Override
    public void onRecruitListFailure(int errorCode, String errorMsg) {
        pullListView.onRefreshComplete(false, false);
        Notification.toast(this, errorMsg);
    }

    @Override
    public void onRecruitListSuccess(List<RecruitListData> list) {
        pullListView.onRefreshComplete(false, false);
        if (null != list) {
            if (0 != currentPage) {
                adapter.addData(list);
            } else {
                adapter.setData(list);
            }
            mList = adapter.getList();
            adapter.notifyDataSetChanged();
            if (mList.size() == 0) {
                noDataTV.setVisibility(View.VISIBLE);
            } else {
                noDataTV.setVisibility(View.GONE);
            }
        }

    }

    OnItemClickListener itemClickListener = new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                                long id) {
            // TODO Auto-generated method stub
            Intent intent = new Intent();
            intent.putExtra(Const.INTENT_JOB_ID, mList.get(position - 1).getId());
            intent.setClass(ComRecruitActivity.this, RecruitDetailsActivity.class);
            startActivity(intent);
        }
    };

    OnRefreshListener onRefreshListener = new OnRefreshListener() {

        @Override
        public void onRefresh() {
            //  上拉刷新 加载请求数据
            pullUpRequest();
        }
    };

    // 上拉刷新数据请求
    private void pullUpRequest() {
        //没有搜索结果 或者数据为空 上拉没有效果
        currentPage++;
        requestData(currentPage * PAGE_COUNTS, PAGE_COUNTS, strPost, strAddress, strSalary, strExperience);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.search_imagebutton01:
                Utils.hideSoftInput(ComRecruitActivity.this, searchET);
                strPost = searchET.getText().toString().trim();
                adapter.clear();
                currentPage = 0;
                requestData(currentPage * PAGE_COUNTS, PAGE_COUNTS, strPost, strAddress, strSalary, strExperience);
                break;

            default:
                break;
        }

    }

    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != manager) {
            manager.removeRecruitListener(this);
        }
    }
}
